package com.springcloud.market.api.service.impl;


import com.springcloud.market.api.entity.Order;
import com.springcloud.market.api.feign.StockFeignService;
import com.springcloud.market.api.mapper.OrderMapper;
import com.springcloud.market.api.service.OrderService;
import com.springcloud.market.api.service.OrderTimeoutSender;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private StockFeignService stockFeignService;

    @Autowired
    private OrderTimeoutSender orderTimeoutSender;

    @Override
    public String createOrder(Order order) {
        // 调用库存服务扣减库存
        String result = stockFeignService.reduceStock(order.getProductId(), 1); // 默认扣减1个库存

        if ("扣减成功".equals(result)) {
            // 保存订单
            orderMapper.insert(order);
            return "下单成功，订单ID：" + order.getId();
        } else {
            return "库存不足，下单失败";
        }
    }

    @GlobalTransactional
    @Override
    public Order create(Order order) {
        orderMapper.insert(order);
        String msg = stockFeignService.seataReduce(order.getProductId());
        System.out.println(msg);

        // 故意异常：余数不能为0
//        int i = 1/0;

        return order;
    }

    @Override
    public Order createOrder() {
        Integer orderId = 202; // 假设这是生成的订单ID
        //发送延迟消息
        try {
            orderTimeoutSender.sendOrderTimeoutMessage(orderId.toString());
        } catch (Exception e) {
            // 记录日志，但通常不应回滚主业务
            System.err.println("发送超时消息失败: " + e.getMessage());
        }
        //返回订单信息。可在订单中加上状态字段，如未支付则取消订单，如支付则执行已支付的逻辑（发送已支付消息，已支付消费者执行）
        return new Order();
    }

}